/**
 * @file 浏览历史记录预加载API
 * @description 为渲染进程提供浏览历史记录相关的API接口
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-08-05
 */

// IPC 通道常量 - 直接定义避免导入主进程模块
// 导入共享的类型定义
import type {
  BrowsingHistory,
  BrowsingHistorySearchOptions,
  DatabaseResult,
  QueryBrowsingHistoryParams,
  UpdateBrowsingHistoryInput
} from '~types/browsing-history'
import { BROWSING_HISTORY_CHANNELS } from '~shared/ipc-topic'

// @ts-ignore
const electron = require('electron')

/**
 * 浏览历史记录API对象
 * @description 提供浏览历史记录的增删改查功能
 */
export const browsingHistory = {
  // ==================== 删除操作 ====================

  /**
   * 删除浏览记录
   * @param id 记录ID
   * @returns Promise<操作结果>
   */
  deleteRecord: async (id: number): Promise<DatabaseResult<void>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.DELETE_RECORD, id)
  },

  /**
   * 批量删除浏览记录
   * @param ids 记录ID数组
   * @returns Promise<操作结果>
   */
  deleteRecords: async (ids: number[]): Promise<DatabaseResult<void>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.DELETE_RECORDS, ids)
  },

  /**
   * 清空所有浏览记录
   * @returns Promise<操作结果>
   */
  clearAllRecords: async (): Promise<DatabaseResult<void>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.CLEAR_ALL_RECORDS)
  },

  // ==================== 查询操作 ====================

  /**
   * 根据ID查找浏览记录
   * @param id 记录ID
   * @returns Promise<查找结果>
   */
  findById: async (id: number): Promise<DatabaseResult<BrowsingHistory | null>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.FIND_BY_ID, id)
  },

  /**
   * 根据URL查找浏览记录
   * @param url URL地址
   * @returns Promise<查找结果>
   */
  findByUrl: async (url: string): Promise<DatabaseResult<BrowsingHistory | null>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.FIND_BY_URL, url)
  },

  /**
   * 查询浏览记录
   * @param params 查询参数
   * @returns Promise<查询结果>
   */
  queryRecords: async (
    params: QueryBrowsingHistoryParams
  ): Promise<DatabaseResult<BrowsingHistory[]>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.QUERY_RECORDS, params)
  },

  /**
   * 搜索浏览记录
   * @param keyword 搜索关键词
   * @param limit 返回记录数量限制
   * @returns Promise<搜索结果>
   */
  searchRecords: async (
    keyword: string,
    limit?: number
  ): Promise<DatabaseResult<BrowsingHistory[]>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.SEARCH_RECORDS, keyword, limit)
  },

  /**
   * 获取最近访问的记录
   * @param limit 返回记录数量限制
   * @returns Promise<查询结果>
   */
  getRecentRecords: async (limit?: number): Promise<DatabaseResult<BrowsingHistory[]>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.GET_RECENT_RECORDS, limit)
  },

  /**
   * 获取访问次数最多的记录
   * @param limit 返回记录数量限制
   * @returns Promise<查询结果>
   */
  getMostVisitedRecords: async (limit?: number): Promise<DatabaseResult<BrowsingHistory[]>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.GET_MOST_VISITED_RECORDS, limit)
  },

  /**
   * 获取记录总数
   * @returns Promise<记录总数>
   */
  getRecordCount: async (): Promise<DatabaseResult<number>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.GET_RECORD_COUNT)
  },

  // ==================== 修改操作 ====================

  /**
   * 更新浏览记录
   * @param input 更新数据
   * @returns Promise<操作结果>
   */
  updateRecord: async (
    input: UpdateBrowsingHistoryInput
  ): Promise<DatabaseResult<BrowsingHistory>> => {
    return electron.ipcRenderer.invoke(BROWSING_HISTORY_CHANNELS.UPDATE_RECORD, input)
  },

  // ==================== 便捷方法 ====================

  /**
   * 搜索历史记录（支持URL和标题）
   * @param query 搜索查询
   * @param options 搜索选项
   * @returns Promise<搜索结果>
   */
  search: async (
    query: string,
    options: BrowsingHistorySearchOptions = {}
  ): Promise<DatabaseResult<BrowsingHistory[]>> => {
    const { limit = 50, searchInUrl = true, searchInTitle = true, timeRange } = options

    // 如果指定了时间范围，使用高级查询
    if (timeRange?.start || timeRange?.end) {
      const queryParams: QueryBrowsingHistoryParams = {
        limit,
        start_time: timeRange.start,
        end_time: timeRange.end,
        order_by: 'visit_time',
        order_direction: 'DESC'
      }

      if (searchInUrl && searchInTitle) {
        // 需要分别查询URL和标题，然后合并结果
        const [urlResults, titleResults] = await Promise.all([
          browsingHistory.queryRecords({ ...queryParams, url_pattern: query }),
          browsingHistory.queryRecords({ ...queryParams, title_pattern: query })
        ])

        if (urlResults.success && titleResults.success) {
          // 合并并去重结果
          const allResults = [...(urlResults.data || []), ...(titleResults.data || [])]
          const uniqueResults = allResults.filter(
            (item, index, arr) => arr.findIndex(t => t.id === item.id) === index
          )

          return {
            success: true,
            data: uniqueResults.slice(0, limit)
          }
        }
      } else if (searchInUrl) {
        queryParams.url_pattern = query
        return browsingHistory.queryRecords(queryParams)
      } else if (searchInTitle) {
        queryParams.title_pattern = query
        return browsingHistory.queryRecords(queryParams)
      }
    }

    // 使用简单搜索
    return browsingHistory.searchRecords(query, limit)
  },

  /**
   * 获取今天的浏览记录
   * @param limit 返回记录数量限制
   * @returns Promise<查询结果>
   */
  getTodayRecords: async (limit = 100): Promise<DatabaseResult<BrowsingHistory[]>> => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)

    return browsingHistory.queryRecords({
      start_time: today.getTime(),
      end_time: tomorrow.getTime(),
      limit,
      order_by: 'visit_time',
      order_direction: 'DESC'
    })
  },

  /**
   * 获取本周的浏览记录
   * @param limit 返回记录数量限制
   * @returns Promise<查询结果>
   */
  getThisWeekRecords: async (limit = 200): Promise<DatabaseResult<BrowsingHistory[]>> => {
    const today = new Date()
    const weekStart = new Date(today)
    weekStart.setDate(today.getDate() - today.getDay())
    weekStart.setHours(0, 0, 0, 0)

    return browsingHistory.queryRecords({
      start_time: weekStart.getTime(),
      limit,
      order_by: 'visit_time',
      order_direction: 'DESC'
    })
  }
}

// 导出类型

export {
  type BrowsingHistory,
  type DatabaseResult,
  type QueryBrowsingHistoryParams,
  type UpdateBrowsingHistoryInput
} from '~types/browsing-history'
